import requests
import json

from common.send_data import send_dingding_data


class SendDingding:

    def __init__(self,url,title):
        self.url = url
        self.title = title

    def send_dingtalk_text(self,data):
        """发送文本消息"""
        headers = {"Content-Type": "application/json"}
        params = {
            "msgtype": "text",
            "text": {
                "content": data
            }
        }
        res = requests.post(url=self.url, headers=headers, json=params, verify=False).json()
        print(res)

    def send_dingtalk_markdown(self,text, file_url=None):
        """发送markdown格式消息，可带附件链接"""
        headers = {"Content-Type": "application/json"}
        # 构建markdown内容
        markdown_content = f"### {self.title}\n\n{text}"
        if file_url:
            markdown_content += f"\n\n[点击查看报告]({file_url})"

        params = {
            "msgtype": "markdown",
            "markdown": {
                "title": self.title,
                "text": markdown_content
            }
        }
        res = requests.post(url=self.url, headers=headers, json=params, verify=False).json()
        print(res)

    def send_dingtalk_with_file(self,text, file_url, btn_text="下载附件"):
        """发送带附件的actionCard消息"""
        headers = {"Content-Type": "application/json"}
        params = {
            "msgtype": "actionCard",
            "actionCard": {
                "title": self.title,
                "text": text,
                "singleTitle": btn_text,
                "singleURL": file_url
            }
        }
        res = requests.post(url=self.url, headers=headers, json=params, verify=False).json()
        print(res)


if __name__ == '__main__':
    url = "https://oapi.dingtalk.com/robot/send?access_token=f10ff68b505c86258af53a46449fefb3f0c53d7e5700a26cf40b70303c9ac981"
    title = "Melynk TEST 环境接口自动化测试报告"
    send = SendDingding(url, title)
    attachment_file_path = 'http://192.168.0.56:63342/melynk_auto/report/report.html?_ijt=sudfe81oahdb85uo3osa8v6tah&_ij_reload=RELOAD_ON_SAVE&sort=result'
    markdown_content = send_dingding_data([1, 1, 1], [1], [1], '•  2025-04-08 15:15:40', 1.3)
    # 发送带附件链接的markdown消息
    send.send_dingtalk_markdown(
        text=markdown_content,
        file_url=attachment_file_path
    )